<template>
  <div class="detail-container">
    <el-card shadow="never">
      <span class="font-title-medium">退货商品</span>
      <el-table border class="standard-margin" ref="productTable" :data="productList">
        <el-table-column label="商品图片" width="160" align="center">
          <template slot-scope="scope">
            <img style="height:80px" :src="scope.row.productPic">
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            <span class="font-small">{{scope.row.productName}}</span><br>
            <span class="font-small">品牌：{{scope.row.productBrand}}</span>
          </template>
        </el-table-column>
        <el-table-column label="价格/货号" width="180" align="center">
          <template slot-scope="scope">
            <span class="font-small">价格：￥{{scope.row.productRealPrice}}</span><br>
            <span class="font-small">货号：NO.{{scope.row.productId}}</span>
          </template>
        </el-table-column>
        <el-table-column label="属性" width="180" align="center">
          <template slot-scope="scope"> {{scope.row.productAttr | formatProductAttr}}</template>
        </el-table-column>
        <el-table-column label="数量" width="100" align="center">
          <template slot-scope="scope">{{scope.row.productCount}}</template>
        </el-table-column>
        <el-table-column label="小计" width="100" align="center">
          <template slot-scope="scope">￥{{totalAmount}}</template>
        </el-table-column>
      </el-table>
      <div style="float:right;margin-top:15px;margin-bottom:15px">
        <span class="font-title-medium">合计：</span>
        <span class="font-title-medium color-danger">￥{{totalAmount}}</span>
      </div>
    </el-card>
    <el-card shadow="never" class="standard-margin">
      <span class="font-title-medium">服务单信息</span>
      <div class="form-container-border">
        <el-row>
          <el-col :span="6" class="form-border form-left-bg font-small">服务单号</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.id}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">申请状态</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.status | formatStatus}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="form-border form-left-bg font-small" style="height:50px;line-height:30px">订单编号
          </el-col>
          <el-col class="form-border font-small" :span="18" style="height:50px">
            {{orderReturnApply.orderSn}}
            <el-button type="text" size="small" @click="handleViewOrder">查看</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">申请时间</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.createTime | formatTime}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">用户账号</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.memberUsername}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">联系人</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.returnName}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">联系电话</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.returnPhone}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">退货原因</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.reason}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">问题描述</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.description}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6" style="height:100px;line-height:80px">凭证图片
          </el-col>
          <el-col class="form-border font-small" :span="18" style="height:100px">
            <el-image v-for="(item,index) in proofPics" :key="index" :src="item" :preview-src-list="proofPics"
              style="width:80px;height:80px;padding:10px;"></el-image>
          </el-col>
        </el-row>
      </div>
      <div class="form-container-border">
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">订单金额</el-col>
          <el-col class="form-border font-small" :span="18">￥{{totalAmount}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">确认退款金额
          </el-col>
          <!-- <el-col class="form-border font-small" style="height:52px" :span="18" 
          v-if="role=='admin'"
          > -->
          <el-col class="form-border font-small" style="height:52px" :span="18">
            ￥<el-input size="small" v-model="updateStatusParam.returnAmount"
              :disabled="orderReturnApply.status !=1||role==='sup'" style="width:200px;margin-left: 10px"></el-input>
          </el-col>
          <!-- <el-col class="form-border font-small" style="height:52px" :span="18" v-if="role=='sup'">
            ￥{{orderReturnApply.returnAmount}}
          </el-col> -->
        </el-row>
        <el-row v-if="(this.role==='admin'||this.role =='sup_admin') && reasonDetail.fareStatus===1">
          <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">
            订单运费金额
          </el-col>
          <el-col class="form-border font-small"
            style="height:52px;line-height: 52px;text-align: left;padding-top: 0;padding-bottom: 0;" :span="18">
            ￥{{freightAmountSource}}
          </el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">
            供应商发货运费
          </el-col>
          <el-col class="form-border font-small" 
            style="height:52px;line-height: 52px;text-align: left;padding-top: 0;padding-bottom: 0;" :span="18">
            ￥{{orderReturnApply.supFreightAmount}}
          </el-col>
        </el-row>
        <div v-if="orderReturnApply.status===0">

          <div v-if="companyAddressList==null || companyAddressList.length <= 0">
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">
                选择收货点
              </el-col>
              <el-col class="form-border font-small" style="height:52px" :span="18">
                <el-button icon="el-icon-plus" size="small" @click="handleAddAddress()" :disabled="role=='admin'">添加地址
                </el-button>
              </el-col>
            </el-row>
          </div>
          <div v-else>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">
                选择收货点
              </el-col>
              <el-col class="form-border font-small" style="height:52px" :span="18">
                <el-select size="small" style="width:200px" :disabled="orderReturnApply.status!==0||role=='admin'"
                  v-model="updateStatusParam.companyAddressId">
                  <el-option v-for="address in companyAddressList" :key="address.id" :value="address.id"
                    :label="address.addressName">
                  </el-option>
                </el-select>
                <el-button icon="el-icon-plus" size="small" @click="handleAddAddress()"
                  :disabled="orderReturnApply.status!==0||role=='admin'">添加地址</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">收货人姓名</el-col>
              <el-col class="form-border font-small" :span="18">{{currentAddress.name}}</el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">所在区域</el-col>
              <el-col class="form-border font-small" :span="18">{{currentAddress | formatRegion}}</el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">详细地址</el-col>
              <el-col class="form-border font-small" :span="18">{{currentAddress.detailAddress}}</el-col>
            </el-row>
            <el-row>
              <el-col class="form-border form-left-bg font-small" :span="6">联系电话</el-col>
              <el-col class="form-border font-small" :span="18">{{currentAddress.phone}}</el-col>
            </el-row>
          </div>
        </div>
        <div v-else>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">退货地址信息</el-col>
            <el-col class="form-border font-small" :span="18">
              {{orderReturnApply.companyAddressDetail}}
            </el-col>
          </el-row>
        </div>
        <div v-if="orderReturnApply.status == 4 || orderReturnApply.status == 6 || orderReturnApply.status == 7">
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">退货物流名称</el-col>
            <el-col class="form-border font-small" :span="18">{{orderReturnApply.deliveryCompany}}</el-col>
          </el-row>
          <el-row>
            <el-col class="form-border form-left-bg font-small" :span="6">退货物流单号</el-col>
            <el-col class="form-border font-small" :span="18">{{orderReturnApply.deliverySn}}</el-col>
          </el-row>
        </div>
      </div>
      <div class="form-container-border" v-show="orderReturnApply.status!==0">
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">处理人员</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.handleMan}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">处理时间</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.handleTime | formatTime}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">处理备注</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.handleNote}}</el-col>
        </el-row>
      </div>
      <div class="form-container-border" v-show="orderReturnApply.status===7">
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">收货人员</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.handleMan}}</el-col>
        </el-row>
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">收货时间</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.receiveTime | formatTime}}</el-col>
        </el-row>
        <!-- <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6">收货备注</el-col>
          <el-col class="form-border font-small" :span="18">{{orderReturnApply.receiveNote}}</el-col>
        </el-row> -->
      </div>
      <div class="form-container-border" v-show="orderReturnApply.status===0&&(role=='sup'||role =='sup_admin')">
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">处理备注
          </el-col>
          <el-col class="form-border font-small" :span="18">
            <el-input size="small" v-model="updateStatusParam.handleNote" style="width:200px;margin-left: 10px"
              :disabled="role=='admin'"></el-input>
          </el-col>
        </el-row>
      </div>
      <!-- <div class="form-container-border" v-show="orderReturnApply.status==1&&role=='admin'">
        <el-row>
          <el-col class="form-border form-left-bg font-small" :span="6" style="height:52px;line-height:32px">收货备注
          </el-col>
          <el-col class="form-border font-small" :span="18">
            <el-input size="small" v-model="updateStatusParam.receiveNote" style="width:200px;margin-left: 10px">
            </el-input>
          </el-col>
        </el-row>
      </div> -->
      <!-- getApplyDetail,rejectApply,confirmReceive,adminCheck,agreeApply,finishReturnApply -->

      <div style="margin-top:15px;text-align: center" v-show="orderReturnApply.status==0&&(role=='sup'||role =='sup_admin')">
        <el-button type="primary" size="small" @click="agreeApply(1)">确认退货</el-button>
        <el-button type="danger" size="small" @click="rejectApply(2)">拒绝退货</el-button>
      </div>
      <div style="margin-top:15px;text-align: center" v-show="orderReturnApply.status==1&&(role=='admin'||role =='sup_admin')">
        <el-button type="primary" size="small" @click="adminCheck(3)">同意申请</el-button>
        <!-- <el-button type="danger" size="small" @click="handleUpdateStatus(6)">拒绝申请</el-button> -->
      </div>
      <div style="margin-top:15px;text-align: center" v-show="orderReturnApply.status==6&&(role=='admin'||role =='sup_admin')">
        <el-button type="primary" size="small" @click="finishReturnApply(7)">同意申请</el-button>
        <!-- <el-button type="danger" size="small" @click="handleUpdateStatus(6)">拒绝申请</el-button> -->
      </div>
      <div style="margin-top:15px;text-align: center" v-show="orderReturnApply.status==4&&(role=='sup'||role =='sup_admin')">
        <el-button type="primary" size="small" @click="confirmReceive(6)">确认收货</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
  import { getApplyDetail, updateApplyStatus, rejectApply, confirmReceive, adminCheck, agreeApply, finishReturnApply } from '@/api/returnApply';
  import { fetchList } from '@/api/companyAddress';
  import { formatDate } from '@/utils/date';
  import { formatProductAttr } from '@/utils/index';
  import { getToken, getRole } from '@/utils/auth'

  const defaultUpdateStatusParam = {
    companyAddressId: null,
    handleMan: 'admin',
    handleNote: null,
    receiveMan: 'admin',
    receiveNote: null,
    returnAmount: 0,
    freightAmount: 0,
    status: 0,
  };
  let changeRoll = function () {
    // console.log('getRole()',getRole());
    if (getRole().indexOf('4') != -1) {
      return 'sup_admin'
    }else if (getRole().indexOf('1') != -1) {
      return 'admin'
    } else if (getRole().indexOf('2') != -1) {
      return 'sup'
    }
  }
  const defaultOrderReturnApply = {
    id: null,
    orderId: null,
    companyAddressId: null,
    productId: null,
    orderSn: null,
    createTime: null,
    memberUsername: null,
    returnAmount: null,
    returnName: null,
    returnPhone: null,
    status: null,
    cancelTime: null,
    receiveStatus: null,
    deliveryCompany: null,
    deliverySn: null,
    deliveryTime: null,
    freightAmount: null,
    handleTime: null,
    productPic: null,
    productName: null,
    productBrand: null,
    productAttr: null,
    productCount: null,
    productPrice: null,
    productRealPrice: null,
    reasonId: null,
    reason: null,
    description: null,
    proofPics: null,
    handleNote: null,
    handleMan: null,
    receiveMan: null,
    receiveTime: null,
    receiveNote: null
  };
  export default {
    name: 'returnApplyDetail',
    data() {
      return {
        id: null,
        orderReturnApply: Object.assign({}, defaultOrderReturnApply),
        productList: null,
        proofPics: [],
        updateStatusParam: Object.assign({}, defaultUpdateStatusParam),
        companyAddressList: null,
        role: changeRoll(),
        reasonDetail: {},
        returnAmountSource: '',
        freightAmountSource: '',
        supFreightAmount: '' // 供应商发货运费
      }
    },
    created() {
      this.id = this.$route.query.id;
      this.getDetail();
    },
    computed: {
      totalAmount() {
        if (this.orderReturnApply != null) {
          return this.orderReturnApply.productRealPrice * this.orderReturnApply.productCount;
        } else {
          return 0;
        }
      },
      currentAddress() {
        let id = this.updateStatusParam.companyAddressId;
        if (this.companyAddressList == null) return {}
        for (let i = 0; i < this.companyAddressList.length; i++) {
          let address = this.companyAddressList[i];
          if (address.id === id) {
            return address;
          }
        }
        return null;
      },
    },
    filters: {
      formatStatus(status) {
        if (status === 0) {
          return "待处理";
        } else if (status === 1) {
          return "已同意";
        } else if (status === 2) {
          return "已拒绝";
        } else if (status === 3) {
          return "待买家发货";
        } else if (status === 4) {
          return "退货中";
        } else if (status === 5) {
          return "买家已取消";
        } else if (status === 6) {
          return "已确认收货";
        } else if (status === 7) {
          return "已完成"
        }
        else {
          return "已拒绝";
        }
      },
      formatTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      },
      formatProductAttr(value) {
        return formatProductAttr(value);
      },
      formatRegion(address) {
        let str = address.province;
        if (address.city != null) {
          str += "  " + address.city;
        }
        str += "  " + address.region;
        return str;
      }
    },
    methods: {
      // changeRoll(){
      //   if(getRole().indexOf('管理员')!= -1){
      //     this.role = 'admin'
      //   }else if(getRole().indexOf('供应商')!= -1){
      //     this.role = 'sup'
      //   }
      // },
      getCurrentAddress(id) {
        if (this.companyAddressList == null) return {}
        for (let i = 0; i < this.companyAddressList.length; i++) {
          let address = this.companyAddressList[i];
          if (address.id === id) {
            return address.province + "," + address.city + "," + address.region + "   " + address.detailAddress +
              "    -    " + address.name + "," + address.phone;
          }
        }
        return null;
      },
      handleAddAddress() {
        this.$router.push('/oms/addCompanyAddress');
      },
      handleViewOrder() {
        this.$router.push({ path: '/oms/orderDetail', query: { id: this.orderReturnApply.orderId } });
      },
      getReasonDetail(id) {
        let data = { id: id }
        this.$http.post("returnReason/getItem", data).then(data => {
          this.reasonDetail = data.info;
        }).catch(error => {
          console.log(error);
        });
      },
      getDetail() {
        getApplyDetail(this.id).then(data => {
          // console.log("getDetail")
          this.orderReturnApply = data.info;
          this.productList = [];
          this.productList.push(this.orderReturnApply);
          if (this.orderReturnApply.proofPics != null) {
            var urls = JSON.parse(this.orderReturnApply.proofPics);
            for (var i = 0; i < urls.length; i++) {
              this.proofPics.push(urls[i].url);
            }
          }

          //console.log(":::" + this.orderReturnApply.freightAmount);
          //退货中和完成
          if (this.orderReturnApply.status === 1 || this.orderReturnApply.status === 4
            || this.orderReturnApply.status === 0 || this.orderReturnApply.status === 7) {
            this.updateStatusParam.returnAmount = this.orderReturnApply.returnAmount;
            this.returnAmountSource = this.updateStatusParam.returnAmount;
            this.freightAmountSource = this.orderReturnApply.freightAmount;
            this.updateStatusParam.companyAddressId = this.orderReturnApply.companyAddressId;
          }
          this.getCompanyAddressList();
          this.getReasonDetail(this.orderReturnApply.reasonId);
        });
      },
      getCompanyAddressList() {
        fetchList().then(data => {
          this.companyAddressList = data.info;
          for (let i = 0; i < this.companyAddressList.length; i++) {
            //if (this.companyAddressList[i].receiveStatus === 1&&this.orderReturnApply.status===0) {
            this.updateStatusParam.companyAddressId = this.companyAddressList[i].id;
            //}
          }
        });
      },
      // rejectApply,confirmReceive,adminCheck,agreeApply,finishReturnApply
      rejectApply() {
        if (!this.updateStatusParam.handleNote) {
          this.$message({
            type: 'success',
            message: '备注不能为空!',
            duration: 1000
          });
          return;
        }
        this.$confirm('是否要进行此操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rejectApply({
            id:this.id,
            handleNote:this.updateStatusParam.handleNote
          }).then(data => {
            this.$message({
              type: 'success',
              message: '操作成功!',
              duration: 1000
            });
            this.$router.back();
          });
        });
      },
      confirmReceive() {
        this.$confirm('是否要进行此操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          confirmReceive({id:this.id}).then(data => {
            this.$message({
              type: 'success',
              message: '操作成功!',
              duration: 1000
            });
            this.$router.back();
          });
        });
      }, adminCheck() {
        // console.log(this.updateStatusParam.freightAmount)
        // console.log(this.freightAmountSource)
        // if (this.updateStatusParam.returnAmount > this.returnAmountSource) {
        //     this.$message({
        //       type: 'success',
        //       message: '退款金额不能超过原金额!',
        //       duration: 1000
        //     });
        //     return
        //   } else if (this.updateStatusParam.freightAmount > this.freightAmountSource) {
        //     this.$message({
        //       type: 'success',
        //       message: '退款运费不能超过原运费!',
        //       duration: 1000
        //     });
        //     return
        //   }
        //   return
        this.$confirm('是否要进行此操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          adminCheck({id:this.id,returnAmount:this.updateStatusParam.returnAmount,freightAmount:this.updateStatusParam.freightAmount}).then(data => {
            this.$message({
              type: 'success',
              message: '操作成功!',
              duration: 1000
            });
            this.$router.back();
          });
        });
      }, agreeApply() {
        if (!this.updateStatusParam.handleNote) {
          this.$message({
            type: 'success',
            message: '备注不能为空!',
            duration: 1000
          });
          return;
        }
        this.$confirm('是否要进行此操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          agreeApply({id:this.id,companyAddressId:this.updateStatusParam.companyAddressId,
            handleNote:this.updateStatusParam.handleNote}).then(data => {
            this.$message({
              type: 'success',
              message: '操作成功!',
              duration: 1000
            });
            this.$router.back();
          });
        });
      }, finishReturnApply() {
        this.$confirm('是否要进行此操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          finishReturnApply({id:this.id}).then(data => {
            this.$message({
              type: 'success',
              message: '操作成功!',
              duration: 1000
            });
            this.$router.back();
          });
        });
      },
    }
  }
</script>
<style scoped>
  .detail-container {
    position: absolute;
    left: 0;
    right: 0;
    width: 1080px;
    padding: 35px 35px 15px 35px;
    margin: 20px auto;
  }

  .standard-margin {
    margin-top: 15px;
  }

  .form-border {
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
  }

  .form-container-border {
    border-left: 1px solid #DCDFE6;
    border-top: 1px solid #DCDFE6;
    margin-top: 15px;
  }

  .form-left-bg {
    background: #F2F6FC;
  }
</style>